﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using HAF.FoundationLib;
using Newtonsoft.Json;
using WareDealer.Helper;
using WareDealer.Mode;

namespace WareDealer.Works
{
    /// <summary>
    /// 优惠采集任务
    /// </summary>
    [DisplayName("优惠采集工作项")]
    public class JdCouponWork : JdWorkItem
    {
        /// <summary>
        /// 优惠信息集合
        /// </summary>
        private readonly List<PrivilegeTag> _promoList = new List<PrivilegeTag>();
        /// <summary>
        /// 执行函数
        /// </summary>
        [DisplayName("执行函数")]
        public override void ExecItem()
        {
            List<ProductInfo> _wareList = WorkItems as List<ProductInfo>;
            if (_wareList == null || _wareList.Count <= 0) return;
            Statu = EnumGatherStatu.Begin;

            Faster.XLogInfo(string.Format("批量采集优惠{0}更新开始", Name));

            _wareList.ForEach(t => _promoList.Add(new PrivilegeTag() { Sku = t.ProductID, Coupon = "", Promo = "", IsEnd = false }));

            int iSplit = 1;
            int iCount = 0;
            List<ProductInfo> splitWares = new List<ProductInfo>();
            foreach (var item in _wareList)
            {
                //GetPromoThread(item);
                //GetWarePromotion(item);
                splitWares.Add(item);
                iCount++;
                iSplit++;
                if (iSplit > 25 || (iCount == _wareList.Count && iSplit <= 25))
                {
                    GetPromoThread(splitWares);
                    splitWares = new List<ProductInfo>();
                    iSplit = 0;
                }
            }

            Stopwatch outManage = new Stopwatch();
            outManage.Start();
            while (true)
            {
                try
                {
                    List<PrivilegeTag> remainWares = _promoList.Where(t => t.IsEnd == false).ToList();
                    if (remainWares.Count == 0)
                    {
                        ResultItems = _promoList;
                        Statu = EnumGatherStatu.End;
                        Faster.XLogInfo(string.Format("批量采集优惠{0}更新完成", Name));
                        break;
                    }
                    else
                    {
                        if (outManage.ElapsedMilliseconds == 300000)
                        {
                            //超时控制5分钟
                            //超时自动设置所有采集为完成状态
                            _promoList.ForEach(t => t.IsEnd = true);
                        }
                    }
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    Faster.XLogErr(ex.Message);
                }
            }

        }

        private void GetPromoThread(List<ProductInfo> wares)
        {
            Thread promoThread = new Thread(delegate() { GetPromoBatch(wares); }) { Name = "promoThread" + wares[0].ProductID, IsBackground = true };
            promoThread.Start();
        }

        private void GetPromoBatch(List<ProductInfo> wares)
        {
            try
            {
                foreach (var item in wares)
                {
                    GetWarePromotion(item);
                    Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                Faster.XLogErr(ex.Message);
            }

        }

        /// <summary>
        /// 获取商品促销信息
        /// </summary>
        /// <param name="myProduct"></param>
        [DisplayName("获取商品促销信息")]
        private void GetWarePromotion(ProductInfo myProduct)
        {
            try
            {
                //http://cd.jd.com/promotion/v2?skuId=1579607941&area=1_72_2799_0&shopId=138013&venderId=142424&cat=1318%2C12102%2C9765&_=1459345921060

                PrivilegeTag nowTag = _promoList.Single(t => t.Sku == myProduct.ProductID);
                if (nowTag != null)
                {
                    string url = string.Format("http://cd.jd.com/promotion/v2?skuId={0}&area={1}&shopId={2}&venderId={3}&cat={4}&_={5}", myProduct.ProductID,
                    SysParams.DispathArea, myProduct.ShopId, myProduct.VenderId, myProduct.Catalog, Golemer.GetTimeStamp(false));
                    string rtnStr = HttpHelper.GetResponseGBK(url, "get", string.Empty);
                    if (string.IsNullOrEmpty(rtnStr) || rtnStr.IndexOf("error", StringComparison.Ordinal) >= 0)
                    {
                        nowTag.IsEnd = true;
                        return;
                    }

                    PromotionMessage promo = JsonConvert.DeserializeObject<PromotionMessage>(rtnStr);
                    if (promo != null)
                    {
                        //myProduct.ProductTag = (promo.ads != null && promo.ads.Count > 0) ? ClearHtml(promo.ads[0].ad) : "";
                        nowTag.Promo = promo.prom.pickOneTag != null && promo.prom.pickOneTag.Count > 0
                            ? Golemer.ClearHtml(promo.prom.pickOneTag[0].content)
                            : "";
                        if (promo.skuCoupon != null && promo.skuCoupon.Count > 0)
                        {
                            //nowTag.Coupon = "";
                            foreach (var item in promo.skuCoupon)
                            {
                                nowTag.Coupon += string.Format("{0}-{1} ", item.quota, item.discount);
                            }
                        }
                    }
                    nowTag.IsEnd = true;
                }
                //if (_waresStatu.ContainsKey(myProduct.ProductID))
                //{
                //    _waresStatu[myProduct.ProductID] = true;
                //}
            }
            catch (Exception ex)
            {
                Faster.XLogErr(ex.Message);
            }
        }
    }
}
